<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Authentication extends CI_Session {

    var $session_name;
    var $ci;
    var $rutes;
    var $field_check;
    var $permissions;
    var $uri;

    function __construct() {
        $this->ci = & get_instance();
        $this->ci->load->config('authentication-settings');

        $this->session_name = $this->ci->config->item('acl_session_name');
        $this->rutes = $this->ci->config->item('acl_rutes');
        $this->field_check = $this->ci->config->item('acl_field_check');
        $this->permissions = $this->ci->config->item('acl_permissions');
        $this->uri = $this->ci->uri;

        $this->check();
    }

    /**
     * Se fija si esta logeado o no.
     * 
     * @param unknown_type $pageLogin
     * @return boolean
     */
    private function isLoggedIn($pageLogin = false) {
        $data = $this->userdata($this->session_name);

        if (( empty($data)) && (!$pageLogin )) {
            $ref['ref'] = current_url();
            $this->set_userdata($ref);
        }

        return (!empty($data));
    }

    /**
     * Chequea permisos.
     * 
     * @param string $field
     * @param array $permissions
     * @return boolean
     */
    private function check() {
        $uri = $this->uri->ruri_string();
        $pageLogin = (strpos($uri, $this->rutes['login']) === false) ? false : true;

        if ($pageLogin) {
            if ($this->isLoggedIn(true)) {
                $this->redirectRef();
            }
        } else {
            $access = $this->requireLogin();

            if (is_array($access)) {
                if ($this->isLoggedIn()) {
                    $dataLogged = $this->getDataLogged();
                    
                    if (!in_array($dataLogged[$this->field_check], $access)) {
                        if (isset($this->rutes[$dataLogged[$this->field_check]])) {
                            redirect($this->rutes[$dataLogged[$this->field_check]]);
                        } else {
                            die('<h1>Error to redirect.</h1>');
                        }
                    }
                } else {
                    redirect($this->rutes['login']);
                }
            }
        }
    }

    /**
     * Se fiaja si la ruta actual necesita permiso de acceso.
     * 
     * @return type 
     */
    private function requireLogin() {
        $return = false;

        $uri = $this->uri->ruri_string();
        
        if (empty($uri)) {
            $uri = $this->rutes['default_controller'];
        }
        
        $arrayuri = explode('/', $uri);
        
        if(count($arrayuri) == 1){
            $uri = $uri . '/index';
        }
        
        foreach ($this->permissions as $permission => $data) {
            $requireLogin = (strpos($uri, $permission) === false) ? false : true;
            
            if ($requireLogin) {
                $return = array_merge((array)$return, (array)$data);;
            }
        }
        
        if(is_array($return)) {
            unset($return[0]);
        }
        
        return $return;
    }

    /**
     * Redirecciona a la url guardada en session o lo redirecciona a la url predefinida del usuario
     * @param string $url 
     * @return void
     */
    private function redirectRef() {
        $ref = $this->userdata('ref');
        $this->unset_userdata('ref');

        if (!empty($ref)) {
            redirect($ref);
        } else {
            $dataLogged = $this->getDataLogged();

            if (isset($this->rutes[$dataLogged[$this->field_check]])) {
                redirect($this->rutes[$dataLogged[$this->field_check]]);
            } else {
                die('<h1>Error to redirect.</h1>');
            }
        }
    }

    /**
     * Crea la sesion y guarda los datos ahi.
     * @param array $data
     * @return void
     */
    public function doLogin($data) {
        $data[$this->session_name] = $data;
        $this->set_userdata($data);
        $this->redirectRef();
    }

    /**
     * Cierra la sesion y deslogea al usuario.
     * @return void
     */
    public function doLogout() {
        $this->unset_userdata($this->session_name);
        $this->destroy();
    }

    /**
     * Devuelve los datos del usuario en sesion.
     * 
     * @return array
     */
    public function getDataLogged() {
        return $this->userdata($this->session_name);
    }

    /**
     * Si no es administrados y no puede ve la causa lo redirecciona
     * 
     * @return array
     */
    public function puedeVerCausa($causaId) {
        $this->ci->load->model('m_causa', 'causa');
        
        $datosusuario = $this->userdata($this->session_name);
        
        if ($datosusuario['tipoId'] != 1 AND !$this->ci->causa->puedeVerCausa($causaId, $datosusuario['estudioId'], $datosusuario['id']))
            redirect('acceso/salir/');
    }
}